package com.ecar.api.service.common.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ecar.api.service.common.AddressService;
import com.ecar.api.support.util.UuidUtils;
import com.ecar.common.dto.DataBean;
import com.ecar.core.common.dao.AddressMapper;
import com.ecar.core.common.entity.Address;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service
@Transactional
public class AddressServiceImpl implements AddressService {
	
	Logger logger = Logger.getLogger(this.getClass());
	
	@Autowired
	AddressMapper addressMapper;

	@Override
	public int deleteByPrimaryKey(String id) {
		// TODO Auto-generated method stub
		return addressMapper.deleteByPrimaryKey(id);
	}
	
	@Override
	public DataBean selectByUserIdAndUserType(String userId, Integer userType) {
		Address address=new Address();
		address.setUserId(userId);
		address.setUserType(userType);
		List<Address> list=addressMapper.selectByUserIdAndUserType(address);
		Map<String, List<Address>> map=new HashMap<String, List<Address>>();
		map.put("address", list);
		if(list.size()==0){
			return new DataBean(200,map,"常用地未设置");
		}
		return new DataBean(200,map,"查询成功");
	}

	@Override
	public DataBean insert(Address record) {
		//该方法里根据用户id,用户类型，地址类型，进行判断
		Address temp=addressMapper.selectByUserIdAndUserTypeAndAddressType(record);
		int pk=0;
		if(temp==null){
			record.setId(UuidUtils.getUUID());
			logger.debug("插入常用地数据: "  + record.toString());
			pk=addressMapper.insert(record);
		}else{
			logger.debug("更新常用地数据: "  + record.toString());
			record.setId(temp.getId());
			pk=addressMapper.updateByPrimaryKeySelective(record);
		}
		if(pk<=0){
			return new DataBean(500,new JSONArray(),"设置常用地失败");
		}
		
		return selectByUserIdAndUserType(record.getUserId(), record.getUserType());
	}

	@Override
	public int insertSelective(Address record) {
		// TODO Auto-generated method stub
		return addressMapper.insertSelective(record);
	}

	@Override
	public Address selectByPrimaryKey(String id) {
		// TODO Auto-generated method stub
		return addressMapper.selectByPrimaryKey(id);
	}

	@Override
	public int updateByPrimaryKeySelective(Address record) {
		// TODO Auto-generated method stub
		return addressMapper.updateByPrimaryKeySelective(record);
	}

	@Override
	public int updateByPrimaryKey(Address record) {
		// TODO Auto-generated method stub
		return addressMapper.updateByPrimaryKey(record);
	}

}
